package com.ruoyi.vehicle.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.vehicle.domain.VehiclePositionVo;
import com.ruoyi.vehicle.service.VehicleLocationService;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tsh
 * @Date: 2025/9/6 09:58
 * @Description: TODO
 **/
@RestController
@RequestMapping("/influx")
@Slf4j
public class InfluxdbController {

    private static final String MEASUREMENT = "vehicle_pos";
    /**
     * Redis GEO存储键
     */
    private static final String REDIS_GEO_KEY = "vehicle:positions";
    @Autowired
    private InfluxDB influxDB;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    VehicleLocationService vehicleLocationService;

    @Autowired
    RedisTemplate redisTemplate;


    //--1 写入数据
    @PostMapping("/writeData")
    public AjaxResult writeData(@RequestBody VehiclePositionVo position) {
        if(position.getTimestamp()==null){
            position.setTimestamp(Instant.now());
        }
        if (position == null || position.getCarId() == null ||
                position.getLatitude() == null || position.getLongitude() == null) {
            return AjaxResult.error("位置数据不完整");
        }

        Point point = Point.measurement(MEASUREMENT)
                .tag("car_id", position.getCarId())
                .addField("lat", position.getLatitude())
                .addField("lon", position.getLongitude())
                .time(position.getTimestamp().toEpochMilli(), TimeUnit.MILLISECONDS)
                .build();


        influxDB.write(point);
        // 写入 Redis GEO
        // 构建地理位置对象
        // 2. 写入Redis GEO
        stringRedisTemplate.opsForGeo().add(REDIS_GEO_KEY,
                new org.springframework.data.geo.Point(position.getLongitude(), position.getLatitude()),
                position.getCarId());
        return AjaxResult.success("写入数据成功");


    }

    /**
     * 查询指定范围内的车辆
     *
     * @param longitude 中心点经度
     * @param latitude  中心点纬度
     * @param radius    半径(公里)
     */
    @GetMapping("/nearby")
    public AjaxResult queryNearbyVehicles(
            @RequestParam Double longitude,  // 经度
            @RequestParam Double latitude,   // 纬度
            @RequestParam(defaultValue = "5000") Double radius // 半径，默认5000米（5公里）
    ) {
       List<VehiclePositionVo> list= vehicleLocationService.queryNearbyVehicles(longitude, latitude, radius);
     return AjaxResult.success(list);
    }
}






